import 'dart:collection';

import 'package:flutter/material.dart';
import 'package:tender_flutter/constant/theme_colors.dart';
import 'package:tender_flutter/http/api_response.dart';
import 'package:tender_flutter/page/home/api/api_home.dart';
import 'package:tender_flutter/page/home/model/company_detail_entity.dart';
import 'package:tender_flutter/router/router.dart';
import 'package:tender_flutter/router/router_map.gr.dart';
import 'package:tender_flutter/style/font_style.dart';
import 'package:tender_flutter/utils/screen_adaper.dart';
import 'package:tender_flutter/widgets/base_appbar.dart';
import 'package:tender_flutter/widgets/load_state_layout.dart';

class CompanyDetailPage extends StatefulWidget {
  /// 公司Key
  final String companyKey;

  /// 公司名称
  final String companyName;

  const CompanyDetailPage({Key key, this.companyKey, this.companyName})
      : super(key: key);

  @override
  _CompanyDetailPageState createState() => _CompanyDetailPageState();
}

class _CompanyDetailPageState extends State<CompanyDetailPage> {
  LoadState _loadState = LoadState.State_Loading;

  Map<String, dynamic> _detailMaps = HashMap();

  /// 公司详情信息
  CompanyDetailEntity _detailEntity;

  /// 公司详情
  Future<ApiResponse<CompanyDetailEntity>> _getDetail() async {
    await Future.delayed(Duration(milliseconds: 400), () async {});
    var response = await ApiHome.companyDetail<CompanyDetailEntity>(
        companyKey: widget.companyKey, companyName: widget.companyName);
    return response;
  }

  FutureBuilder<ApiResponse<CompanyDetailEntity>> _buildFutureBuilder() {
    return FutureBuilder(
        future: _getDetail(),
        builder: (BuildContext context,
            AsyncSnapshot<ApiResponse<CompanyDetailEntity>> snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            if (snapshot.hasData) {
              _detailEntity = snapshot.data.result;
            }
            if (_detailEntity != null) {
              _loadState = LoadState.State_Success;
              _handelDatas();
            } else {
              _loadState = LoadState.State_Error;
            }
          }
          return LoadStateLayout(
            state: _loadState,
            bgColor: ThemeColors.colorWhite,
            successWidget: _loadState == LoadState.State_Success
                ? _initBody()
                : Container(),
          );
        });
  }

  /// 包装数据
  _handelDatas() {
    _detailMaps["企业名称"] = _detailEntity.companyName ?? "";
    _detailMaps["信用代码"] = _detailEntity.regNumber ?? "";
    _detailMaps["法人"] = _detailEntity.faRen ?? "";
    _detailMaps["注册资金"] = _detailEntity.regMoney ?? "";
    _detailMaps["企业类型"] = _detailEntity.companyType ?? "";
    _detailMaps["注册类型"] = _detailEntity.regType ?? "";
    _detailMaps["注册时间"] = _detailEntity.createDate ?? "";
    _detailMaps["经营状态"] = _detailEntity.businessStatus ?? "";
    _detailMaps["证书有效时间"] = _detailEntity.invalidTime ?? "";
    _detailMaps["邮箱"] = _detailEntity.email;
    _detailMaps["网址"] = _detailEntity.webSite;
    _detailMaps["电话"] = _detailEntity.phone;
    _detailMaps["地址"] = _detailEntity.address;
  }

  @override
  void initState() {
    super.initState();

    /// 页面渲染完成之后的回调，只执行一次
    // WidgetsBinding.instance.addPostFrameCallback((mag) {
    //   // _companyKey = RouteData.of(context).queryParams["companyKey"].stringValue;
    //   // _getDetail();
    // });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: ThemeColors.colorWhite,
        appBar: _initAppBar(),
        body: _buildFutureBuilder());
  }

  /// 导航
  Widget _initAppBar() {
    return BaseAppBar(context, Text("企业详情", style: FonStyle.navTextStyle()));
  }

  /// 内容
  Widget _initBody() {
    return SingleChildScrollView(
        physics: BouncingScrollPhysics(),
        child: Column(children: [
          _getTitleItem("基本信息"),
          _initBaseInfoView(),
          _getDivider(),
          _getTitleItem("股权信息"),
          _initGuDongView(),
          _getButtonView()
        ]));
  }

  /// 标题
  Widget _getTitleItem(String title) {
    return Container(
        margin: EdgeInsets.symmetric(
            vertical: ScreenAdapter.height(20),
            horizontal: ScreenAdapter.width(20)),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Container(
                margin: EdgeInsets.only(
                    top: ScreenAdapter.height(10),
                    right: ScreenAdapter.width(15)),
                height: ScreenAdapter.height(20),
                width: ScreenAdapter.width(4),
                color: ThemeColors.colorType6),
            Text(title,
                style: TextStyle(
                    color: ThemeColors.colorType1,
                    fontSize: ScreenAdapter.sp(30),
                    fontWeight: FontWeight.bold))
          ],
        ));
  }

  /// 基本信息
  Widget _initBaseInfoView() {
    return Container(
        // width: double.infinity,
        margin: EdgeInsets.symmetric(
            vertical: ScreenAdapter.height(20),
            horizontal: ScreenAdapter.width(20)),
        child: Column(children: [
          Table(
            //所有列宽
            columnWidths: const {
              //列宽
              0: FixedColumnWidth(150),
              1: FixedColumnWidth(200),
            },
            defaultVerticalAlignment: TableCellVerticalAlignment.middle,
            //表格边框样式
            border: TableBorder.all(
              width: 0.5,
              color: ThemeColors.colorType47,
              style: BorderStyle.solid,
            ),
            children: _detailMaps.keys
                .map((e) => _getTableCell(e, _detailMaps[e]))
                .toList(),
          ),
          Table(
            //所有列宽
            columnWidths: const {
              //列宽
              0: FixedColumnWidth(350),
            },
            defaultVerticalAlignment: TableCellVerticalAlignment.middle,
            border: TableBorder(
                left: BorderSide(
                  width: 0.5,
                  color: ThemeColors.colorType47,
                  style: BorderStyle.solid,
                ),
                right: BorderSide(
                  width: 0.5,
                  color: ThemeColors.colorType47,
                  style: BorderStyle.solid,
                ),
                bottom: BorderSide(
                  width: 0.5,
                  color: ThemeColors.colorType47,
                  style: BorderStyle.solid,
                )),
            children: [
              TableRow(children: [
                Container(
                    padding: EdgeInsets.symmetric(
                        vertical: ScreenAdapter.height(20),
                        horizontal: ScreenAdapter.width(20)),
                    child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: [
                          Text(
                            "经营范围",
                            style: TextStyle(
                                color: ThemeColors.colorType24,
                                fontSize: ScreenAdapter.sp(28),
                                fontWeight: FontWeight.w500),
                          ),
                          SizedBox(height: ScreenAdapter.height(20)),
                          Text(
                            _detailEntity.bussinessDes ?? "",
                            style: TextStyle(
                                color: ThemeColors.colorType7,
                                fontSize: ScreenAdapter.sp(28),
                                fontWeight: FontWeight.w400),
                          )
                        ]))
              ])
            ],
          ),
        ]));
  }

  TableRow _getTableCell(String title, dynamic content) {
    return TableRow(children: [
      Container(
        // height: ScreenAdapter.height(70),
        padding: EdgeInsets.symmetric(
            vertical: ScreenAdapter.height(20),
            horizontal: ScreenAdapter.width(20)),
        alignment: Alignment.centerLeft,
        child: Text(
          title,
          style: TextStyle(
              color: ThemeColors.colorType24,
              fontSize: ScreenAdapter.sp(28),
              fontWeight: FontWeight.w500),
        ),
      ),
      Container(
        // height: ScreenAdapter.height(70),
        padding: EdgeInsets.symmetric(
            vertical: ScreenAdapter.height(15),
            horizontal: ScreenAdapter.width(20)),
        alignment: Alignment.centerLeft,
        child: Text(
          content.toString(),
          style: TextStyle(
              color: ThemeColors.colorType7,
              fontSize: ScreenAdapter.sp(28),
              fontWeight: FontWeight.w400),
        ),
      ),
    ]);
  }

  /// 股东视图
  Widget _initGuDongView() {
    return Container(
        margin: EdgeInsets.symmetric(
            vertical: ScreenAdapter.height(20),
            horizontal: ScreenAdapter.width(20)),
        child: ListView.separated(
          shrinkWrap: true,
          physics: const NeverScrollableScrollPhysics(),
          itemCount: _detailEntity.gqBeans.length,
          itemBuilder: (BuildContext context, int index) {
            return _getGGItem(_detailEntity.gqBeans[index]);
          },
          separatorBuilder: (BuildContext context, int index) {
            return Divider(
              height: 1,
              color: ThemeColors.colorType49,
            );
          },
        ));
  }

  /// 股东信息item
  Widget _getGGItem(CompanyPersonalEntity entity) {
    return Container(
      margin: EdgeInsets.only(bottom: ScreenAdapter.height(30)),
      padding: EdgeInsets.all(ScreenAdapter.width(30)),
      decoration: BoxDecoration(
          color: ThemeColors.colorWhite,
          border: Border.all(color: ThemeColors.colorType45, width: 0.5),
          borderRadius: BorderRadius.circular(ScreenAdapter.width(15))),
      child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text(entity.gdName,
                style: TextStyle(
                    fontSize: ScreenAdapter.sp(30),
                    color: ThemeColors.colorBlack,
                    fontWeight: FontWeight.w500)),
            SizedBox(height: ScreenAdapter.height(20)),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
                  Text("持股比例",
                      style: TextStyle(
                        fontSize: ScreenAdapter.sp(28),
                        color: ThemeColors.colorType14,
                      )),
                  SizedBox(height: ScreenAdapter.height(10)),
                  Text(entity.proportion,
                      style: TextStyle(
                        fontSize: ScreenAdapter.sp(28),
                        fontWeight: FontWeight.w500,
                        color: ThemeColors.colorBlack,
                      ))
                ]),
                Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
                  Text("认缴出资额",
                      style: TextStyle(
                        fontSize: ScreenAdapter.sp(28),
                        color: ThemeColors.colorType14,
                      )),
                  SizedBox(height: ScreenAdapter.height(10)),
                  Text(entity.money + entity.unit,
                      style: TextStyle(
                        fontSize: ScreenAdapter.sp(28),
                        fontWeight: FontWeight.w500,
                        color: ThemeColors.colorBlack,
                      ))
                ]),
                Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
                  Text("持股类型",
                      style: TextStyle(
                        fontSize: ScreenAdapter.sp(28),
                        color: ThemeColors.colorType14,
                      )),
                  SizedBox(height: ScreenAdapter.height(10)),
                  Text(entity.property,
                      style: TextStyle(
                        fontSize: ScreenAdapter.sp(28),
                        fontWeight: FontWeight.w500,
                        color: ThemeColors.colorBlack,
                      ))
                ]),
              ],
            )
          ]),
    );
  }

  /// 横线
  Widget _getDivider() {
    return Container(
        width: double.infinity,
        height: ScreenAdapter.height(10),
        color: ThemeColors.colorType11);
  }

  /// 三个按钮视图
  Widget _getButtonView() {
    return Container(
      margin: EdgeInsets.only(
          left: ScreenAdapter.width(20),
          right: ScreenAdapter.width(20),
          bottom: ScreenAdapter.height(30)),
      // padding: EdgeInsets.all(ScreenAdapter.width(30)),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          GestureDetector(
              onTap: () {
                LRouter.navigatorCtx(context).push(Routes.companyMasterPage,
                    arguments: CompanyMasterPageArguments(
                        companyKey: _detailEntity.companyKey,
                        companyName: _detailEntity.companyName));
              },
              child: Container(
                width: ScreenAdapter.width(210),
                height: ScreenAdapter.height(60),
                alignment: Alignment.center,
                decoration: BoxDecoration(
                    color: ThemeColors.colorType58,
                    borderRadius:
                        BorderRadius.circular(ScreenAdapter.width(10))),
                child: Text(
                  "分支机构",
                  style: TextStyle(
                      color: ThemeColors.colorWhite,
                      fontSize: ScreenAdapter.sp(30),
                      fontWeight: FontWeight.w500),
                ),
              )),
          GestureDetector(
              onTap: () {
                LRouter.navigatorCtx(context).push(Routes.companyInvestmentPage,
                    arguments: CompanyInvestmentPageArguments(
                        companyKey: _detailEntity.companyKey,
                        companyName: _detailEntity.companyName));
              },
              child: Container(
                width: ScreenAdapter.width(210),
                height: ScreenAdapter.height(60),
                alignment: Alignment.center,
                decoration: BoxDecoration(
                    color: ThemeColors.colorType59,
                    borderRadius:
                        BorderRadius.circular(ScreenAdapter.width(10))),
                child: Text(
                  "对外投资",
                  style: TextStyle(
                      color: ThemeColors.colorWhite,
                      fontSize: ScreenAdapter.sp(30),
                      fontWeight: FontWeight.w500),
                ),
              )),
          GestureDetector(
              onTap: () {
                LRouter.navigatorCtx(context).push(Routes.companyChangePage,
                    arguments: CompanyChangePageArguments(
                        companyKey: _detailEntity.companyKey,
                        companyName: _detailEntity.companyName));
              },
              child: Container(
                width: ScreenAdapter.width(210),
                height: ScreenAdapter.height(60),
                alignment: Alignment.center,
                decoration: BoxDecoration(
                    color: ThemeColors.colorType60,
                    borderRadius:
                        BorderRadius.circular(ScreenAdapter.width(10))),
                child: Text(
                  "变更信息",
                  style: TextStyle(
                      color: ThemeColors.colorWhite,
                      fontSize: ScreenAdapter.sp(30),
                      fontWeight: FontWeight.w500),
                ),
              ))
        ],
      ),
    );
  }
}
